/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

package com.facebook.imageutils;

import com.facebook.media.ExifInterface;
import com.facebook.common.logging.FLog;
import com.facebook.soloader.DoNotOptimize;
import ohos.media.image.ImageSource;
import ohos.media.image.common.PropertyKey;

import java.io.InputStream;

/**
 * Specialization of EXIF utilities for HEIF files. The specialization allows us to restrict
 * ourselves to {@link ExifInterface} can wrap around an input stream. Actual
 * support for HEIF was added.
 */
public class HeifExifUtil {

  public static final String TAG = "HeifExifUtil";

  public static int getOrientation(final InputStream inputStream) {
      return HeifExifUtilAN.getOrientation(inputStream);
  }

  @DoNotOptimize
  private static class HeifExifUtilAN {

    static int getOrientation(final InputStream inputStream) {
      try {
        ImageSource.SourceOptions opts = new ImageSource.SourceOptions();
        opts.formatHint = "image/png";
        ImageSource imageSource = ImageSource.create(inputStream,opts);

        return imageSource.getImagePropertyInt(
                PropertyKey.Exif.ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
      } catch (final Exception e) {
        FLog.d(TAG, "Failed reading Heif Exif orientation -> ignoring", e);
        return ExifInterface.ORIENTATION_UNDEFINED;
      }
    }
  }
}
